package com.cskaoyan._03equals;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/14 15:49
 **/
/*
    源码:
    public boolean equals(Object obj) {
        return (this == obj);
    }
    说明:
        参数需要传一个对象
        默认实现: 判断当前这个对象是否跟参数对象一样
 */
public class Demo {
    public static void main(String[] args) {
        Student s1 = new Student("zs", 20);
        Student s2 = new Student("zs", 20);
        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s1));
        System.out.println("----------");

        Teacher t = new Teacher("ls", 30);
        SonTeacher sonTeacher = new SonTeacher("ls", 30);
        System.out.println(t.equals(sonTeacher));

    }
}


class Student{
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        // 自反性
        if (this == o) return true;
        // 排他性
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;
        // 比较成员变量的值
        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}


class Teacher{
    String name;
    int age;

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 使用instanceof
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        // if (o == null || getClass() != o.getClass()) return false;
        if (o == null) return false;
        // 类型扩大
        if (!(o instanceof Teacher)) return false;

        Teacher teacher = (Teacher) o;

        if (age != teacher.age) return false;
        return name != null ? name.equals(teacher.name) : teacher.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

class SonTeacher extends Teacher{
    String name;
    int age;

    public SonTeacher(String name, int age) {
        super(name, age);
    }


}